<?php

/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */


/**
 * Description of Order
 *
 * @author Administrator
 */

namespace Api\Api\Order;
use Api\Api\Base;
class Order extends Base {
    //put your code here
    private $orderModel;
    
    function __construct() {
        parent::__construct();
        $this->orderModel = M("Order");
    }
    
    function trade_add($data){
        $data['info_string']=  json_decode($data['info_string'],1);
        $orderinfo=$data['info_string']['order'];
        $orderinfo['state']=1;//默认已支付
        if(!$orderinfo['ref']){
            $this->setError(self::ORDER_ID_ERROR, "ORDER_ID为空");
            return false;
        }
        if(!addOrder($orderinfo,$imsg)){
            $this->setError(self::ADD_FAIL, $imsg);
            return FALSE;
        }
        return true;
    }
    /**
     * 退货Api  更改订单状态为退款
     * @param type $data
     * @return boolean
     */
    function trade_return($data){
        print_r( $data );die;
        //退款状态为4
        $where=array(
            'ref'=>$data['ref'],
            'channel_code'=>$this->get_channel_code($data['app_id']),
        );
        $order=$this->orderModel->where($where)->find();
        if(!$order){
            $this->_error="订单不存在";
            return false;
        }
        if($order['state']==4){
            return true;
        }
        if($this->orderModel->where($where)->save(array('state'=>4))){
           return true; 
        }else{
            $this->_error="订单状态更新失败";
            return false;
        }
    }
    
    /**
     * 国内订单入库
     */
    public function domestic_order_add( $data ) {
        //平台标示认证
        if( !$platform = M('customer_platform_bind')->where( array('identification' => $data['identification'] , 'customer_id' => $data['app_id']))->find() ) {
            $this->_error = '平台不存在';
            return false;
        }
        $this->orderModel->startTrans();
        //默认设置已支付
        $data['platform_id'] = $platform['id'];
        $data['state'] = 1;
        $data['distribution_customer_id'] = $data['app_id']; //分销商ID
        $data['supply_customer_id'] = M('Goods')->alias('g')->join('__GOODS_DISTRIBUTION__ gd ON gd.goods_id = g.id')->where(array('g.earn13' => $data['order_line'][0]['earn13'] , 'gd.customer_id'))->getField('gd.supply_customer_id'); //供应商ID
        //订单中台创建日期
        $data['create_time'] = date('Y-m-d H:i:s');
        //组合数据
        if( $this->orderModel->create( $data ) === false ) {
            $this->orderModel->rollback();
            $this->_error = $this->orderModel->getError();
            return false;
        }
        //数据库入库
        if( !$order_id = $this->orderModel->add() ) {
            $this->orderModel->rollback();
            $this->_error = '订单同步失败，请重新同步';
            return false;
        }
        
        $order_line = array(); //订单商品入库信息
        //入库商品信息
        foreach( $data['order_line'] as $key => $value ) {
            $supply_info = M('Goods')->alias('g')->join('__GOODS_DISTRIBUTION__ gd ON gd.goods_id = g.id')->where(array('g.earn13' => $value['earn13'] , 'gd.customer_id' => $data['app_id']))->field('gd.type,gd.goods_supply_id AS supply_product_id,gd.id AS distribution_product_id,gd.goods_id,gd.cost_price,gd.supply_customer_id')->find(); //获得供货商品ID和分销商品ID
            $order_goods_stock_num = $value['stock_num'];//购买的库存
            if( $value['type'] == 2 ){ //锁货模式
                $now_stock_num = abs( $order_goods_stock_num );  //当前库存
                $order_goods_stock_num = $supply_info['stock_num'] - $now_stock_num;
                $stock_num = ($order_goods_stock_num < 0 ? $v['stock_num'] : $now_stock_num);
                $order_line[] = array(
                    'order_id'                  => $order_id,
                    'ref'                       => $value['ref'],
                    'name'                      => $value['name'],
                    'price'                     => $value['price'],
                    'num'                       => $stock_num,
                    'sub_total'                 => $value['sub_total'],
                    'sub_total_untaxed'         => $value['sub_total'],
                    'create_time'               => date('Y-m-d H:i:s'),
                    'date_order'                => $data['date_order'],
                    'supply_price'              => $supply_info['cost_price'],
                    'supply_product_id'         => $supply_info['supply_product_id'],
                    'distribution_product_id'   => $supply_info['distribution_product_id'],
                    'supply_customer_id'        => $supply_info['supply_customer_id'],
                    'goods_id'                  => $supply_info['goods_id'],
                    'pay_type'                  => 'LINE',
                    'pay_status'                => 1,
                    'source_type'               => 1
                );
                //库存减少 并且锁库
                $dec_stock_num = $v['stock_num'] - $stock_num;
                M('goods_distribution')->where(array('id' => $supply_info['distribution_product_id']))->save(array( 'stock_num' => $dec_stock_num )); //减少锁货库存
                M('goods_supply')->where(array('id' => $supply_info['supply_product_id']))->setInc('lock_stock_num' , $stock_num); //增加供应商仓库库存锁货
            }
            if( $value['type'] == 1 && $order_goods_stock_num > 0 ) { //共享模式
                //获得供应商的供应产品信息
                $supply_goods_info = M('goods_supply')->where(array('goods_id' => $goods_id,'_string' => '`stock_num` > 0'))->order('acting_price ASC')->select();
                if( $supply_goods_info ) {
                    foreach( $supply_goods_info as $k => $v ) {
                        $now_stock_num = abs( $order_goods_stock_num );  //当前库存
                        $order_goods_stock_num = $v['stock_num'] - $now_stock_num; //检测仓库库存是否足够
                        $stock_num = ($order_goods_stock_num < 0 ? $v['stock_num'] : $now_stock_num);
                        $order_line[] = array(
                            'order_id'                  => $order_id,
                            'ref'                       => $value['ref'],
                            'name'                      => $value['name'],
                            'price'                     => $value['price'],
                            'num'                       => $stock_num,
                            'sub_total'                 => $value['sub_total'],
                            'sub_total_untaxed'         => $value['sub_total'],
                            'create_time'               => date('Y-m-d H:i:s'),
                            'date_order'                => $data['date_order'],
                            'supply_price'              => $v['acting_price'],
                            'supply_product_id'         => $v['id'],
                            'distribution_product_id'   => $supply_info['distribution_product_id'],
                            'supply_customer_id'        => $v['customer_id'],
                            'goods_id'                  => $v['goods_id'],
                            'source_type'               => 2
                        );
                        //库存减少 并且锁库
                        $dec_stock_num = $v['stock_num'] - $stock_num;
                        M('goods_supply')->where(array('id' => $v['id']))->save(array('lock_stock_num' => $v['lock_stock_num'] + $stock_num , 'stock_num' => $dec_stock_num ));//增加供应商仓库库存锁货
                        if( $order_goods_stock_num >= 0 )   continue; //库存分配完成之后跳出循环
                    }
                }
            }
        }
        if( M('order_line')->addAll( $order_line ) === false ) {
            $this->orderModel->rollback();
            $this->_error = '订单同步失败，请重新同步';
            return false;
        }
        
        //入库商品支付信息
        foreach( $data['order_payment'] as $key => $value ) {
            $data['order_payment'][$key]['order_id'] = $order_id;
            $data['order_payment'][$key]['ref'] = $data['ref'];
            $data['order_payment'][$key]['create_time'] = date('Y-m-d H:i:s');
        }
        if( M('order_payment')->addAll( $data['order_payment'] ) === false ) {
            $this->orderModel->rollback();
            $this->_error = '订单同步失败，请重新同步';
            return false;
        }
        M('system_prompt')->add(array(
            'customer_id' => $data['app_id'],
            'type' => 1,
            'target_id' => $data['ref'],
            'title' => '您的平台【' .$platform['name']. '】有新订单同步',
            'create_time' => time()
        ));
        $this->orderModel->commit();
        return true; 
    }
}